﻿/* $RCSFile: CrmEditSiteMap.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmEditSiteMap/CrmEditSiteMap.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:48  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;
using CrmSdk.CRM4;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using System.IO;


namespace AddonNice.PageModules.CrmEditSiteMap
{
    public class AStr
    {
        public const string Backup                  =   "CRM_EDITSITEMAP_BACKUP";
    }

	/// <summary>
    /// Initializer class for CrmEditSiteMap 
    /// </summary>
    public class CrmEditSiteMapSI : PortalCRMModuleControlSI
    {
        public CrmEditSiteMapSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditSiteMapSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditSiteMapSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditSiteMapSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            string extgrp                       =   pm.ExtendedResourcesGroup;

            SettingItemSpecial ShowContacts     =   new SettingItemSpecial(AStr.Backup,new BooleanDataType());
            ShowContacts.Value                  =   StStr.strTrue;
            ShowContacts.Order                  =   10;
            ShowContacts.ExtendedGroupName      =   extgrp;
            ShowContacts.EnglishName            =   "Backup before save";
            ShowContacts.Description            =   "Backup all customizations before saving changes.";
            bSettings.AddSetting(ShowContacts);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEditSiteMapSI InitSettings END.",ModuleTraceSwitch.Sw.Info);

        }
    }

    public partial class CrmEditSiteMap : PortalCRMModuleControl
    {
        const string strCatSiteMap  =   "SiteMap";
        const string strCatArea     =   "Area";
        const string strCatGroup    =   "Group";
        const string strCatSubArea  =   "SubArea";

        #region Properties

        string _LCID    = System.Threading.Thread.CurrentThread.CurrentCulture.LCID.ToString();
        public string LCID
        {
            get
            {
                return _LCID;
            }
        }
        
        #endregion Properties
        
        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General implementation

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return new Guid("{0F9F2269-8992-4c3e-92A8-3AEE2026240E}");
            }
        }
        #endregion General implementation


        public CrmEditSiteMap()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEditSiteMap Ctor BEG.",ModuleTraceSwitch.Sw.Info);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEditSiteMap Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
        
        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "CRMEDITISV";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmEditSiteMapSI(bSettings,this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // will be enabled by opening the file
                updateBtn.Enabled       =   false;
                CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
                util.ExportXml();
                LoadSiteMapTree(util);
            }
        }

        void LoadSiteMapTree(CrmUtil4SiteMap util)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap LoadSiteMapTree BEG.",ModuleTraceSwitch.Sw.Info);
            TreeUtil fTree          =   util.BuildDetailledTree();
            FillTreeView(fTree);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap LoadSiteMapTree END.",ModuleTraceSwitch.Sw.Info);
        }

        void LoadSiteMap()
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string strSiteMap       =   util.ExportXml(); 
            TbSiteMap.Text          =   XmlValidator.FormatXml(strSiteMap);
        }

        void OpenBtn_Click(object sender, ImageClickEventArgs e)
        {
                LoadSiteMap();
                updateBtn.Enabled   =   true;
        }


        void FillTreeView(TreeUtil fTree)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap FillTreeView BEG fTree: {0}",fTree.Node.Text),ModuleTraceSwitch.Sw.Info);
            RadSiteMapTree.UnselectAllNodes();
            RadSiteMapTree.Nodes.Clear();
            RadTreeNode nd0     =   new RadTreeNode(fTree.Node.Text);
            RadSiteMapTree.Nodes.Add(nd0);
            nd0.Expanded        = true;
            nd0.Category        = strCatSiteMap;
            FillNodes(nd0, fTree.Node);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap FillTreeView END Nodes.Count: {0}",RadSiteMapTree.Nodes.Count),ModuleTraceSwitch.Sw.Info);
        }

        private void FillNodes(RadTreeNode nd0, NodeUtil ndu)
        {
            for (int i = 0; i < ndu.Nodes.Count; i++)
            {
                NodeUtil nu         =   ndu.Nodes[i];
                RadTreeNode nd      =   new RadTreeNode(nu.Text);
                switch (nu.Type)
                {
                    case NodeType.Area:
                        nd.Category =   strCatArea;
                        nd.Expanded =   true; // We expand only areas, should we ?
                        break;
                    case NodeType.Group:
                        nd.Category =   strCatGroup;
                        break;
                    case NodeType.SubArea:
                        nd.Category =   strCatSubArea;
                        break;
                }
                nd0.Nodes.Add(nd);
                FillNodes(nd, nu);
            }
        }
        
        public string ValidateSiteMapXml(string xml)
        {
            try 
            {
                string pagePath             =   Server.MapPath(Config.ModulesPath+"/CrmEditSiteMap/ISVConfigAndSiteMap.xsd");
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap ValidateSiteMapXml pagePath: {0}",pagePath),ModuleTraceSwitch.Sw.Info);
                FileInfo pageFile           =   new FileInfo(pagePath);
                string schemaPath           =   System.IO.Path.Combine(pageFile.Directory.FullName, "ISVConfigAndSiteMap.xsd");
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap ValidateSiteMapXml schemaPath: {0}",schemaPath),ModuleTraceSwitch.Sw.Info);

                XmlValidator validator      =   new XmlValidator(schemaPath);
                XmlDocument Metadata        =   new XmlDocument();
                Metadata.LoadXml(xml);
                string path                 =   "//SiteMap";
                XmlNode SiteMapNode         =   Metadata.SelectSingleNode(path);
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap ValidateSiteMapXml SiteMapNode.InnerXml: {0}",SiteMapNode.InnerXml),ModuleTraceSwitch.Sw.Info);
                return validator.Validate(SiteMapNode.InnerXml);
            }

            catch (Exception ex) 
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap ValidateSiteMapXml ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        string ExtractId(RadTreeNode destNode)
        {
            string strId        =   string.Empty;
            if ( destNode != null )
            {
                int idx         =   destNode.Text.IndexOf("Id='");
                strId           =   destNode.Text.Substring(idx+4);
                idx             =   strId.IndexOf("'");
                strId           =   strId.Substring(0,idx);
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap ExtractId  Id: '{0}'.",strId),ModuleTraceSwitch.Sw.Info);
            return strId;
        }

        void ReOrderSubArea(RadTreeNode destNode, RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string firstSubAreaId   =   ExtractId(destNode);
            string nextSubAreaId    =   ExtractId(sourceNode);
            util.ReOrderSubArea(firstSubAreaId,nextSubAreaId,true);
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap ReOrderSubArea END.",ModuleTraceSwitch.Sw.Info);
        }

        void ReOrderGroup(RadTreeNode destNode, RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string firstId          =   ExtractId(destNode);
            string nextId           =   ExtractId(sourceNode);
            util.ReOrderGroup(firstId,nextId,true);
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap ReOrderGroup END.",ModuleTraceSwitch.Sw.Info);
        }

        void ReOrderArea(RadTreeNode destNode, RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string firstId          =   ExtractId(destNode);
            string nextId           =   ExtractId(sourceNode);
            util.ReOrderArea(firstId,nextId,true);
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap ReOrderArea END.",ModuleTraceSwitch.Sw.Info);
        }

        void NewSubArea(RadTreeNode GroupNode,RadTreeNode destNode,RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string nextSubAreaId    =   ExtractId(destNode);
            string GroupId          =   ExtractId(GroupNode);
            string AreaId           =   ExtractId(GroupNode.ParentNode);
            int PassParam           =   0;
            string entityNm         =   string.Empty;
            string url              =   string.Empty;
            string langCode         =   LCID;
            string strTitle         =   string.Empty;
            string strId            =   string.Empty;
            foreach(RadTreeNode nd in sourceNode.Nodes)
            {
                if ( nd.Category == "Id" )
                    strId           =   nd.Text;
                else if ( nd.Category == "Title" )
                    strTitle        =   nd.Text;
                else if ( nd.Category == "Url" )
                    url             =   nd.Text;
                else if ( nd.Category == "entity" )
                    entityNm        =   nd.Text;
                else if ( nd.Category == "PassParam" )
                    PassParam        =   nd.Checked ? 1:0;
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewSubArea  AreaId: {0}, GroupId: {1}.",AreaId,GroupId),ModuleTraceSwitch.Sw.Info);
            if ( !string.IsNullOrEmpty(url) )
                 util.AddNewSubArea(AreaId,GroupId,nextSubAreaId,NewSubArea(strId,PassParam,url,langCode,strTitle),strId,true);
            else if ( !string.IsNullOrEmpty(entityNm) )
                util.AddNewSubArea(AreaId,GroupId,nextSubAreaId,NewSubArea(strId,entityNm,langCode,strTitle),strId,true);
            else
            {
                string msg          =   LocalizeHelper.Localize("EDITSITEMAP_INCOMPLETE_MODEL","Incomplete model, check values");
                lblErr.Text         =   msg;
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmEditSiteMap NewSubArea no Url or entityName END.",ModuleTraceSwitch.Sw.Info);
                return;
            }
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap NewSubArea  END.",ModuleTraceSwitch.Sw.Info);
        }
        
        /// <summary>
        /// Version with entity
        /// </summary>
        string NewSubArea(string id,string entityNm,string langCode,string Title)
        {
            string str  =   string.Format( "<SubArea Id=\"{0}\" Entity=\"{1}\" ><Titles><Title LCID=\"{2}\" Title=\"{3}\" /></Titles></SubArea>",
                new object[]{id,entityNm,langCode,Title});
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewSubArea : {0}",str),ModuleTraceSwitch.Sw.Info);
            return str;
        }
        
        /// <summary>
        /// Version with url
        /// </summary>
        string NewSubArea(string id,int PassParam,string url,string langCode,string Title)
        {
            string str  =   string.Format( "<SubArea Id=\"{0}\" PassParams=\"{1}\" Url=\"{2}\" ><Titles><Title LCID=\"{3}\" Title=\"{4}\" /></Titles></SubArea>",
                new object[]{id,PassParam,url,langCode,Title});
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewSubArea : {0}",str),ModuleTraceSwitch.Sw.Info);
            return str;
        }
        
        void NewGroup(RadTreeNode GroupNode,RadTreeNode destNode,RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string AreaId           =   ExtractId(GroupNode);
            bool isWorkPlace        =   AreaId.Equals("Workplace");
            string nextGroupId      =   ExtractId(destNode);
            bool IsProfile          =   false;
            string langCode         =   LCID;
            string strTitle         =   string.Empty;
            string strDesc          =   string.Empty;
            string strId            =   string.Empty;
            foreach(RadTreeNode nd in sourceNode.Nodes)
            {
                if ( nd.Category == "Id" )
                    strId           =   nd.Text;
                else if ( nd.Category == "Title" )
                    strTitle        =   nd.Text;
                else if ( nd.Category == "Description" )
                    strDesc         =   nd.Text;
                else if ( nd.Category == "IsProfile" )
                    IsProfile        =   nd.Checked;
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewGroup  AreaId: {0}, nextGroupId: {1}.",AreaId,nextGroupId),ModuleTraceSwitch.Sw.Info);
            if ( !string.IsNullOrEmpty(strId) && !string.IsNullOrEmpty(strTitle) )
                util.AddNewGroup(AreaId,nextGroupId,NewGroup(isWorkPlace,strId,IsProfile,langCode,strTitle,strDesc),strId,true);
            else
            {
                string msg          =   LocalizeHelper.Localize("EDITSITEMAP_INCOMPLETE_MODEL","Incomplete model, check values");
                lblErr.Text         =   msg;
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmEditSiteMap NewSubArea no Url or entityName END.",ModuleTraceSwitch.Sw.Info);
                return;
            }
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap NewGroup  END.",ModuleTraceSwitch.Sw.Info);
        }
        
        string NewGroup(bool isWorkPlace,string id,bool IsProfile,string langCode,string Title,string Description)
        {
            string str  =   string.Empty;
            // IsProfile is only available in workplace Area
            if (isWorkPlace)
                str     =   string.Format("<Group Id=\"{0}\" IsProfile=\"{1}\"><Titles><Title LCID=\"{2}\" Title=\"{3}\" /></Titles><Descriptions><Description LCID=\"{2}\" Description=\"{4}\"/></Descriptions></Group>",
                                            new object[]{id,IsProfile,langCode,Title,Description});
            else str    =   string.Format("<Group Id=\"{0}\" ><Titles><Title LCID=\"{1}\" Title=\"{2}\" /></Titles><Descriptions><Description LCID=\"{1}\" Description=\"{3}\"/></Descriptions></Group>",
                                                new object[]{id,langCode,Title,Description});
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewGroup : {0}",str),ModuleTraceSwitch.Sw.Info);
            return str;
        }

        void NewArea(RadTreeNode destNode,RadTreeNode sourceNode)
        {
            CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
            string nextAreaId       =   ExtractId(destNode);

            string langCode         =   LCID;
            string strTitle         =   string.Empty;
            string strIcon          =   string.Empty;
            string strDesc          =   string.Empty;
            string strId            =   string.Empty;
            foreach(RadTreeNode nd in sourceNode.Nodes)
            {
                if ( nd.Category == "Id" )
                    strId           =   nd.Text;
                else if ( nd.Category == "Title" )
                    strTitle        =   nd.Text;
                else if ( nd.Category == "Icon" )
                    strIcon         =   nd.Text;
                else if ( nd.Category == "Description" )
                    strDesc         =   nd.Text;
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewArea nextAreaId: {0}.",nextAreaId),ModuleTraceSwitch.Sw.Info);
            if ( !string.IsNullOrEmpty(strId) && !string.IsNullOrEmpty(strTitle) )
                util.AddNewArea(nextAreaId,NewArea(strId,langCode,strIcon,strTitle,strDesc),strId,true);
            else
            {
                string msg          =   LocalizeHelper.Localize("EDITSITEMAP_INCOMPLETE_MODEL","Incomplete model, check values");
                lblErr.Text         =   msg;
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmEditSiteMap NewSubArea no Url or entityName END.",ModuleTraceSwitch.Sw.Info);
                return;
            }
            // Relaod TreeView
            LoadSiteMapTree(util);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap NewArea END.",ModuleTraceSwitch.Sw.Info);
        }
        
        string NewArea(string id,string langCode,string IconUrl,string Title,string Description)
        {
            string str  =   string.Format("<Area Id=\"{0}\" Icon='{1}'><Titles><Title LCID=\"{2}\" Title=\"{3}\" /></Titles><Descriptions><Description LCID=\"{2}\" Description=\"{4}\"/></Descriptions></Area>",
                new object[]{id,IconUrl,langCode,Title,Description});
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap NewArea : {0}",str),ModuleTraceSwitch.Sw.Info);
            return str;
        }

 		/// <summary>
		/// User has moved a node
		/// </summary>
        void RadSiteMapTree_NodeDrop(object sender, RadTreeNodeDragDropEventArgs e)
        {
            // Fetch event data 
            RadTreeNode sourceNode		= e.SourceDragNode;
            RadTreeNode destNode		= e.DestDragNode;
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap RadSiteMapTree_NodeDrop  {0}.",sourceNode.Text),ModuleTraceSwitch.Sw.Info);
    
            // node may have been dropped outside treeviews, or on itself
			// we can't move to root (destNode.Parent == null)
			// We don't accept inversing hierarchy
			if (destNode == null || sourceNode.Equals(destNode) || sourceNode.IsAncestorOf(destNode) )
				return;

			RadTreeViewDropPosition d	=	e.DropPosition;

			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap RadSiteMapTree_NodeDrop  {0} -{1}- {2}",sourceNode.Text,d,destNode.Text),ModuleTraceSwitch.Sw.Info);
			try
			{
                string sourceCat        =   sourceNode.Category;
                string destCat          =   destNode.Category;
                bool sameTree           =   sourceNode.TreeView.Equals(destNode.TreeView);
				if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap RadSiteMapTree_NodeDrop: sourceCat: {0}, destCat: {1}", sourceCat, destCat),ModuleTraceSwitch.Sw.Info);
				switch (sourceCat)
				{
					case strCatArea:
                        if (destCat == strCatSiteMap)
                        {
                            if ( !sameTree )
                                NewArea(null,sourceNode);
                        }
                        else if (destCat == strCatArea)
                        {
                            if ( !sameTree )
                                NewArea(destNode,sourceNode);
                            else ReOrderArea(destNode,sourceNode);
                        }
						break;
					case strCatGroup:
                        if (destCat == strCatArea)
                        {
                            if ( ! sameTree )
                                NewGroup(destNode,null,sourceNode);
                        }
                        else if (destCat == strCatGroup)
                        {
                            if ( ! sameTree )
                                NewGroup(destNode.ParentNode,destNode,sourceNode);
                            else ReOrderGroup(destNode,sourceNode);
                        }
						break;
					case strCatSubArea:
                        if (destCat == strCatGroup)
                        {
                            if ( ! sameTree )
                                NewSubArea(destNode,null,sourceNode);
                        }
                        else if (destCat == strCatSubArea)
                        {
                            if ( ! sameTree )
                                NewSubArea(destNode.ParentNode,destNode,sourceNode);
                            else ReOrderSubArea(destNode,sourceNode);
                        }
						break;
					default:
						return;
				}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEditSiteMap RadSiteMapTree_NodeDrop END.",ModuleTraceSwitch.Sw.Info);
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap RadSiteMapTree_NodeDrop ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
			}
        }

        // ????????? needed to save change !
        void RadTemplatesTree_NodeEdit(object sender, RadTreeNodeEditEventArgs e)
        {
            e.Node.Text = e.Text;
        }

        void RadSiteMapTree_NodeEdit(object sender, RadTreeNodeEditEventArgs e)
        {
            
        }

        void SetError(string errMSg)
        {
            lblErr.Text         =   errMSg;
            lblErr.CssClass     =   "Error";
        }


        void CrmEditSiteMap_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            /* pb
            string errMSg           =   ValidateSiteMapXml(TbSiteMap.Text);
            if ( !string.IsNullOrEmpty(errMSg) )
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap CrmEditSiteMap_ADNUpdateModule Page not valid Msg: {0}",errMSg),ModuleTraceSwitch.Sw.Info);
                e.Cancel            =   true;
                lblErr.Text         =   errMSg;
                return;
            }*/
            try
            {
                bool backup             =   Settings[AStr.Backup].ToBool();
                bool ret                =   false;
                if ( backup )
                {
                    ret                 =   Wrapper.Util.BackupCustomizations();
                    if ( CRMTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEditSiteMap CrmEditSiteMap_ADNUpdateModule BackupCustomizations success: {0}.",ret),CRMTraceSwitch.Sw.Info);
                    // failed, we can't continue without backup
                    if ( !ret )
                    {
                        string msg      =   "[E]CrmEditSiteMap CrmEditSiteMap_ADNUpdateModule failed, stopping save.";
                        if ( CRMTraceSwitch.Sw.TraceError )
                            Trace2.WriteLine(msg,CRMTraceSwitch.Sw.Info);
                        SetError(LocalizeHelper.Localize("CRM_BACKUP_ERR","Error in backup"));
                        e.Cancel            =   true;
                        return;
                    }
                }
                CrmUtil4SiteMap util    =   new CrmUtil4SiteMap((CrmWrapper4)Wrapper);
                ret                     =   util.UpdateSiteMap(TbSiteMap.Text,true);
                if (!ret)
                {
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("Error: {0}",util.errMsg);
                    SetError(sb.ToString());
                    e.Cancel            =   true;
                    return;
                }
            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap CrmEditSiteMap_ADNUpdateModule soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                StringBuilder sb        =   new StringBuilder();
                sb.AppendFormat("Error: <br />{0}<br />",ErrorCodes.GetErrorMessage(sex));
                SetError(sb.ToString());
                e.Cancel                =   true;
                return;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEditSiteMap CrmEditSiteMap_ADNUpdateModule ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }
        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + strcult;
            updateBtn2.SkinID   =   "Update_" + strcult;
            OpenBtn.SkinID      =   "Open_" + strcult;
        }

        #region Std overrides

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                +=  new System.EventHandler(this.Page_Load);
            ADNUpdateModule                     +=  new PortalModuleEventHandler(CrmEditSiteMap_ADNUpdateModule);
            OpenBtn.Click                       +=  new ImageClickEventHandler(OpenBtn_Click);
            RadSiteMapTree.NodeDrop             +=  new RadTreeViewDragDropEventHandler(RadSiteMapTree_NodeDrop);
            RadTemplatesTree.NodeDrop           +=  new RadTreeViewDragDropEventHandler(RadSiteMapTree_NodeDrop);
            RadTemplatesTree.NodeEdit           +=  new RadTreeViewEditEventHandler(RadTemplatesTree_NodeEdit);
            RadSiteMapTree.NodeEdit             +=  new RadTreeViewEditEventHandler(RadSiteMapTree_NodeEdit);
            }


        #endregion Std overrides
 
    }
}